import os
import threading

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from common.base.controller import Controller
from common import logger
from conf.config import Config
from utils.sql_app.database import init_tortoise


class FastSkeletonApp:

    _instance_lock = threading.Lock()
    app = None
    init_routes = None

    @classmethod
    def instance(cls, init_routes, title="Et Admin API接口文档管理系统"):
        with FastSkeletonApp._instance_lock:
            if not hasattr(FastSkeletonApp, "_instance"):
                FastSkeletonApp._instance = FastSkeletonApp(init_routes, title)

        return FastSkeletonApp._instance

    def __init__(self, init_routes, title="Et Admin API接口文档管理系统"):
        self.app = FastAPI(
            docs_url=None,
            redoc_url=None,
            title=title, version='1.0'
        )

        self.init_routes = init_routes
        Controller.init_app(self.app)
        self.init()

    def init(self):

        self.app.mount(
            '/static',
            StaticFiles(directory=os.path.join(Config.BASE_DIR, 'static')),
            name='static'
        )

        # 批量导入注册路由
        self.init_routes(self.app)

        # 注册中间件
        from api_middleware.middleware import middleware
        middleware(self.app)

        @self.app.on_event("startup")
        async def startup_event():
            await init_tortoise()
            logger.info(f"[ENV] {os.environ.get('api_env', 'dev').upper()}环境")
            logger.info(f"[Api] 项目启动")

        @self.app.on_event("shutdown")
        async def shutdown_event():
            logger.info(f"[Api] 项目关闭")


